package com.example.blue;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.blue.ui.DynamicWaveFormView;

import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;


public class OulajiaoActivity extends AppCompatActivity implements DataProcessorManager.DataUpdateListener,DataProcessorManagerRight.DataUpdateListener{
    private static final String TAG = "OulajiaoActivity";
    private String deviceId;
    private Spinner spinner;
    private Spinner spinnerHand;
    private Integer selectedSensorNum=0;
    private Integer selectedHandNum=0;
    private BluetoothService bluetoothService;
    private Boolean isBound=false;
    private DynamicWaveFormView waveformViewX;
    private DynamicWaveFormView waveformViewY;
    private DynamicWaveFormView waveformViewZ;
    private Thread workerThreadx;
    private Thread workerThready;
    private Thread workerThreadz;
    private Boolean runningx=false;
    private Boolean runningy=false;
    private Boolean runningz=false;
    private Handler handler = new Handler(Looper.getMainLooper());
    private DataProcessorManager processorManager;
    private DataProcessorManagerRight processorManagerRight;
    private final ConcurrentLinkedQueue<Float> magxDataQueue = new ConcurrentLinkedQueue<>();
    private final ConcurrentLinkedQueue<Float> magyDataQueue = new ConcurrentLinkedQueue<>();
    private final ConcurrentLinkedQueue<Float> magzDataQueue = new ConcurrentLinkedQueue<>();
//    private ConcurrentLinkedQueue<byte[]> dataQueue = new ConcurrentLinkedQueue<>();
//    private ConcurrentLinkedQueue<byte[]> dataQueue2 = new ConcurrentLinkedQueue<>();
private LinkedBlockingDeque<byte[]> dataQueue = new LinkedBlockingDeque<>();
    private LinkedBlockingDeque<byte[]> dataQueue2 = new LinkedBlockingDeque<>();
    private Integer conDeviceNum=1;
    private String deviceMacLeft;
    private String deviceMacRight;
    private Boolean isJiaozhun1=false;
    private Boolean isJiaozhun2=false;
    private Integer handDir=0;
    private Boolean isLeftDeviceReceived=false;
    private Boolean isRightDeviceReceived=false;

    private final ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
            bluetoothService = binder.getService();
            isBound = true;
            Log.d("ServiceTest", "onServiceConnected: bound=" + isBound);
            if(conDeviceNum==1){
                if(handDir==1) {
                    dataQueue  = bluetoothService.getDataQueueLeft();
                    processorManager = DataProcessorManager.getInstance(dataQueue);
                }else{
                    dataQueue2  = bluetoothService.getDataQueueRight();
                    processorManager = DataProcessorManager.getInstance(dataQueue2);
                }
                processorManager.setDataUpdateListener(OulajiaoActivity.this);
                processorManager.startProcessing();
                processorManager.setProcessingFunction(ProcessingFunction.Allout);
            }
            else{
                dataQueue  = bluetoothService.getDataQueueLeft();
                dataQueue2  = bluetoothService.getDataQueueRight();
                processorManager = DataProcessorManager.getInstance(dataQueue);
                processorManager.setDataUpdateListener(OulajiaoActivity.this);
                processorManager.startProcessing();
                processorManager.setProcessingFunction(ProcessingFunction.Allout);

                processorManagerRight=DataProcessorManagerRight.getInstance(dataQueue2);
                processorManagerRight.setDataUpdateListener(OulajiaoActivity.this);
                processorManagerRight.startProcessing();
                processorManagerRight.setProcessingFunction(ProcessingFunction.Allout);
            }

        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CrashHandler.getInstance().init(this);
        setContentView(R.layout.activity_oulajiao);
        // 开启返回箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(null);
        getSupportActionBar().setTitle("传感器欧拉角");

        SharedPreferences sp = getSharedPreferences("my_cache", Context.MODE_PRIVATE);
        conDeviceNum = sp.getInt("conDeviceNum", 1);
        isLeftDeviceReceived=sp.getBoolean("isLeftDeviceReceived",false);
        isRightDeviceReceived=sp.getBoolean("isRightDeviceReceived",false);
        if(conDeviceNum==1) {

            handDir = sp.getInt("handDirection",0);
            if(handDir==1){
                if(isLeftDeviceReceived==false){
                    Toast.makeText(OulajiaoActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                }
                deviceId = sp.getString("DEVICE_ADDRESS_LEFT", "");
            }else{
                if(isRightDeviceReceived==false){
                    Toast.makeText(OulajiaoActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                }
                deviceId = sp.getString("DEVICE_ADDRESS_RIGHT", "");
            }
        }
        if(conDeviceNum==2){
            if(isLeftDeviceReceived==false){
                Toast.makeText(OulajiaoActivity.this, "左手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
            }else if(isRightDeviceReceived==false){
                Toast.makeText(OulajiaoActivity.this, "右手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
            }
            deviceMacLeft = sp.getString("DEVICE_ADDRESS_LEFT","");
            deviceMacRight=sp.getString("DEVICE_ADDRESS_RIGHT","");
        }

        waveformViewX = findViewById(R.id.waveformView1);
        waveformViewY = findViewById(R.id.waveformView2);
        waveformViewZ = findViewById(R.id.waveformView3);
        waveformViewX.setYtitle("X轴欧拉角(deg)");
        waveformViewX.setYRange(-180,180);
        waveformViewY.setYtitle("Y轴欧拉角(deg)");
        waveformViewY.setYRange(-180,180);
        waveformViewZ.setYtitle("Z轴欧拉角(deg)");
        waveformViewZ.setYRange(-180,180);

        spinner = findViewById(R.id.modeSpinner);
        String[] options = {"传感器1", "传感器2", "传感器3", "传感器4", "传感器5", "传感器6"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_item,
                options
        );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selected = options[position];
                if(position!=selectedSensorNum){
                    waveformViewX.clearDataPoints();
                    waveformViewY.clearDataPoints();
                    waveformViewZ.clearDataPoints();
                }
                selectedSensorNum=position;
               // Toast.makeText(OulajiaoActivity.this, "选择了: " + selectedSensorNum, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        spinnerHand = findViewById(R.id.modeSpinnerHand);
        if(conDeviceNum==2) {
            String[] options2 = {"左手", "右手"};
            ArrayAdapter<String> adapter2 = new ArrayAdapter<>(
                    this,
                    android.R.layout.simple_spinner_item,
                    options2
            );
            adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerHand.setAdapter(adapter2);
            spinnerHand.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    if (position != selectedHandNum) {
                        waveformViewX.clearDataPoints();
                        waveformViewY.clearDataPoints();
                        waveformViewZ.clearDataPoints();
                    }
                    selectedHandNum = position;
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });
        }else{
            spinnerHand.setVisibility(View.GONE);
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        if(conDeviceNum==1) {
            if(handDir==1) {
                Intent intent = new Intent(this, BluetoothService.class);
                intent.putExtra("DEVICE_ADDRESS_LEFT", deviceId);
                bindService(intent, connection, Context.BIND_AUTO_CREATE);
            }else{
                Intent intent = new Intent(this, BluetoothService.class);
                intent.putExtra("DEVICE_ADDRESS_RIGHT", deviceId);
                bindService(intent, connection, Context.BIND_AUTO_CREATE);
            }
        }
        if(conDeviceNum==2) {
            Intent intent = new Intent(this, BluetoothService.class);
            intent.putExtra("DEVICE_ADDRESS_LEFT", deviceMacLeft);
            intent.putExtra("DEVICE_ADDRESS_RIGHT", deviceMacRight); // 如果需要
            bindService(intent, connection, Context.BIND_AUTO_CREATE);
        }

    }

    @Override
    public void onDataProcessed(ProcessedData data) {
        String processedValue = data.getAngle();
        //  dataTextView.setText("收到数据: " + processedValue);
        String flag = data.getFlag();
        System.out.println("oulajiao-Flag:"+flag);
        System.out.println("oulajiao-Hex: " + processedValue);
        if(flag.equals("fileNull")){
            Toast.makeText(this,"缺少文件",Toast.LENGTH_SHORT).show();
            return;
        }
        if(flag.equals("allout")){
            String[] dataArr = processedValue.split(" ");
            if(selectedHandNum==0) {
                switch (selectedSensorNum) {
                    case 0:
                        String da1 = dataArr[0].length() > 10 ? dataArr[0].substring(0, 8) : dataArr[0];
                        String da2 = dataArr[1].length() > 10 ? dataArr[1].substring(0, 8) : dataArr[1];
                        String da3 = dataArr[2].length() > 10 ? dataArr[2].substring(0, 8) : dataArr[2];
                        waveformViewX.addDataPoint(Float.parseFloat(da1));
                        waveformViewY.addDataPoint(Float.parseFloat(da2));
                        waveformViewZ.addDataPoint(Float.parseFloat(da3));
                        break;
                    case 1:
                        String dd1 = dataArr[3].length() > 10 ? dataArr[3].substring(0, 8) : dataArr[3];
                        String dd2 = dataArr[4].length() > 10 ? dataArr[4].substring(0, 8) : dataArr[4];
                        String dd3 = dataArr[5].length() > 10 ? dataArr[5].substring(0, 8) : dataArr[5];

                        waveformViewX.addDataPoint(Float.parseFloat(dd1));
                        waveformViewY.addDataPoint(Float.parseFloat(dd2));
                        waveformViewZ.addDataPoint(Float.parseFloat(dd3));
                        break;
                    case 2:
                        String de1 = dataArr[6].length() > 10 ? dataArr[6].substring(0, 8) : dataArr[6];
                        String de2 = dataArr[7].length() > 10 ? dataArr[7].substring(0, 8) : dataArr[7];
                        String de3 = dataArr[8].length() > 10 ? dataArr[8].substring(0, 8) : dataArr[8];

                        waveformViewX.addDataPoint(Float.parseFloat(de1));
                        waveformViewY.addDataPoint(Float.parseFloat(de2));
                        waveformViewZ.addDataPoint(Float.parseFloat(de3));
                        break;
                    case 3:
                        String df1 = dataArr[9].length() > 10 ? dataArr[9].substring(0, 8) : dataArr[9];
                        String df2 = dataArr[10].length() > 10 ? dataArr[10].substring(0, 8) : dataArr[10];
                        String df3 = dataArr[11].length() > 10 ? dataArr[11].substring(0, 8) : dataArr[11];

                        waveformViewX.addDataPoint(Float.parseFloat(df1));
                        waveformViewY.addDataPoint(Float.parseFloat(df2));
                        waveformViewZ.addDataPoint(Float.parseFloat(df3));
                        break;
                    case 4:
                        String dc1 = dataArr[12].length() > 10 ? dataArr[12].substring(0, 8) : dataArr[12];
                        String dc2 = dataArr[13].length() > 10 ? dataArr[13].substring(0, 8) : dataArr[13];
                        String dc3 = dataArr[14].length() > 10 ? dataArr[14].substring(0, 8) : dataArr[14];

                        waveformViewX.addDataPoint(Float.parseFloat(dc1));
                        waveformViewY.addDataPoint(Float.parseFloat(dc2));
                        waveformViewZ.addDataPoint(Float.parseFloat(dc3));
                        break;
                    case 5:
                        String db1 = dataArr[15].length() > 10 ? dataArr[15].substring(0, 8) : dataArr[15];
                        String db2 = dataArr[16].length() > 10 ? dataArr[16].substring(0, 8) : dataArr[16];
                        String db3 = dataArr[17].length() > 10 ? dataArr[17].substring(0, 8) : dataArr[17];

                        waveformViewX.addDataPoint(Float.parseFloat(db1));
                        waveformViewY.addDataPoint(Float.parseFloat(db2));
                        waveformViewZ.addDataPoint(Float.parseFloat(db3));
                        break;
                }
            }

        }
    }
     @Override
    public void onDataProcessedRight(ProcessedData data) {
        String processedValue = data.getAngle();
        //  dataTextView.setText("收到数据: " + processedValue);
        String flag = data.getFlag();
        System.out.println("oulajiao-Flag:"+flag);
         if(flag.equals("fileNull")){
             Toast.makeText(this,"缺少文件",Toast.LENGTH_SHORT).show();
             return;
         }
        if(flag.equals("allout")){
            String[] dataArr = processedValue.split(" ");
            if(selectedHandNum==1) {
                switch (selectedSensorNum) {
                    case 0:
                        String da1 = dataArr[0].length() > 10 ? dataArr[0].substring(0, 8) : dataArr[0];
                        String da2 = dataArr[1].length() > 10 ? dataArr[1].substring(0, 8) : dataArr[1];
                        String da3 = dataArr[2].length() > 10 ? dataArr[2].substring(0, 8) : dataArr[2];
                        waveformViewX.addDataPoint(Float.parseFloat(da1));
                        waveformViewY.addDataPoint(Float.parseFloat(da2));
                        waveformViewZ.addDataPoint(Float.parseFloat(da3));
                        break;
                    case 1:
                        String dd1 = dataArr[3].length() > 10 ? dataArr[3].substring(0, 8) : dataArr[3];
                        String dd2 = dataArr[4].length() > 10 ? dataArr[4].substring(0, 8) : dataArr[4];
                        String dd3 = dataArr[5].length() > 10 ? dataArr[5].substring(0, 8) : dataArr[5];

                        waveformViewX.addDataPoint(Float.parseFloat(dd1));
                        waveformViewY.addDataPoint(Float.parseFloat(dd2));
                        waveformViewZ.addDataPoint(Float.parseFloat(dd3));
                        break;
                    case 2:
                        String de1 = dataArr[6].length() > 10 ? dataArr[6].substring(0, 8) : dataArr[6];
                        String de2 = dataArr[7].length() > 10 ? dataArr[7].substring(0, 8) : dataArr[7];
                        String de3 = dataArr[8].length() > 10 ? dataArr[8].substring(0, 8) : dataArr[8];

                        waveformViewX.addDataPoint(Float.parseFloat(de1));
                        waveformViewY.addDataPoint(Float.parseFloat(de2));
                        waveformViewZ.addDataPoint(Float.parseFloat(de3));
                        break;
                    case 3:
                        String df1 = dataArr[9].length() > 10 ? dataArr[9].substring(0, 8) : dataArr[9];
                        String df2 = dataArr[10].length() > 10 ? dataArr[10].substring(0, 8) : dataArr[10];
                        String df3 = dataArr[11].length() > 10 ? dataArr[11].substring(0, 8) : dataArr[11];

                        waveformViewX.addDataPoint(Float.parseFloat(df1));
                        waveformViewY.addDataPoint(Float.parseFloat(df2));
                        waveformViewZ.addDataPoint(Float.parseFloat(df3));
                        break;
                    case 4:
                        String dc1 = dataArr[12].length() > 10 ? dataArr[12].substring(0, 8) : dataArr[12];
                        String dc2 = dataArr[13].length() > 10 ? dataArr[13].substring(0, 8) : dataArr[13];
                        String dc3 = dataArr[14].length() > 10 ? dataArr[14].substring(0, 8) : dataArr[14];

                        waveformViewX.addDataPoint(Float.parseFloat(dc1));
                        waveformViewY.addDataPoint(Float.parseFloat(dc2));
                        waveformViewZ.addDataPoint(Float.parseFloat(dc3));
                        break;
                    case 5:
                        String db1 = dataArr[15].length() > 10 ? dataArr[15].substring(0, 8) : dataArr[15];
                        String db2 = dataArr[16].length() > 10 ? dataArr[16].substring(0, 8) : dataArr[16];
                        String db3 = dataArr[17].length() > 10 ? dataArr[17].substring(0, 8) : dataArr[17];

                        waveformViewX.addDataPoint(Float.parseFloat(db1));
                        waveformViewY.addDataPoint(Float.parseFloat(db2));
                        waveformViewZ.addDataPoint(Float.parseFloat(db3));
                        break;
                }
            }

        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish(); // 结束当前Activity，返回上一个
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(conDeviceNum==1) {
            processorManager.setProcessingFunction(ProcessingFunction.Blank);
            processorManager.setzero();
            processorManager.stopProcessing();
        }else {
            processorManager.setProcessingFunction(ProcessingFunction.Blank);
            processorManager.setzero();
            processorManager.stopProcessing();
            processorManagerRight.setProcessingFunction(ProcessingFunction.Blank);
            processorManagerRight.setzero();
            processorManagerRight.stopProcessing();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(conDeviceNum==1) {
            processorManager.setProcessingFunction(ProcessingFunction.Blank);
            processorManager.setzero();
            processorManager.stopProcessing();
        }else {
            processorManager.setProcessingFunction(ProcessingFunction.Blank);
            processorManager.setzero();
            processorManager.stopProcessing();
            processorManagerRight.setProcessingFunction(ProcessingFunction.Blank);
            processorManagerRight.setzero();
            processorManagerRight.stopProcessing();
        }
    }
}